import React, { useState, useCallback } from "react";
import { Button, List } from "antd-mobile";
import { Common } from 'UtilsCommon';
import Base from './base';
import * as styles from '../styles/view.scss';

export default (props) => {
    const { property, view, pageAxis } = Base.getProps(props);

    const [isVisible, setIsVisible] = useState(property.isVisible !== false && property.isDataRight !== false);
    const [loading, setLoading] = useState(false);
    const [disabled, setDisabled] = useState(!!property.disabled);
    const [text, setText] = useState(property.text);
    const [, setRefreshId] = useState(null);

    const clickAction = useCallback(() => {
        if (property.eventActionName) pageAxis.invokeEventAction(property.eventActionName, { property, view, pageAxis });
        else if (property.eventAction) pageAxis.invokeEventAction2(property.eventAction, { property, view, pageAxis });
    }, [property, view, pageAxis]);

    property.setIsVisible = (v) => { property.isVisible = v; setIsVisible(v); };
    property.setDisabled = (v) => setDisabled(v);
    property.setLoading = (l) => setLoading(l);
    property.setText = (v) => setText(v);
    property.refresh = () => setRefreshId(Common.createGuid());

    if (!isVisible) return null;

    const { style, divClassName, isListItem, color, isDiv } = property;

    const className = Base.getClassName(property, styles);

    const renderButton = () => <Button onClick={clickAction}
        className={className}
        style={style}
        disabled={disabled}
        shape={property.shape}
        loading={loading}
        fill={property.fill}
        size={property.size}
        color={color}>{text}</Button>;

    if (isListItem) return <List.Item className={styles.divButton}>{renderButton()}</List.Item>;
    if (isDiv) return <div className={styles[divClassName]}>{renderButton()}</div>;

    return renderButton();
};
